import { Table, Tabs } from 'antd';
import { connect } from 'umi';
import { useEffect, useMemo, useState, useRef } from 'react';
import { getTableColumns } from '../mconfig/Tablecolumn';
import { ManageService } from '../services';
import { Form, Space, Button, DatePicker, Card, Row } from 'antd';
import { SearchOutlined, DownloadOutlined } from '@ant-design/icons';
import pageStyles from '@/common/pageLayout.less';
import moment from 'moment';
import * as ExcelJs from "exceljs";
import {saveAs} from "file-saver";
import {Workbook} from "exceljs";
import {Worksheet} from "exceljs";

const AssetDeprecitionClassManageView: React.FC<AssetDeprecitionClassManageAPI.IManageType> = ({ curRes }) => {

  const tableRef = useRef<any>(null);

    // 详情数据
    const [type, setType] = useState<String>('1');
    
    // 详情数据
    const [dataSource, setDataSource] = useState<any>([]);

    const manageServiceCallback = (res) => {
      setDataSource(res?.obj)
    }

    /**  获取管理页数据 */
    const { manageServiceReturnRun, manageServiceReturnLoading } = ManageService(manageServiceCallback, curRes);
    /** 搜索表单form */
    const [searchForm] = Form.useForm();

    const getTableColumn: Record<string, any>[] = useMemo(() => {
        return getTableColumns();
    }, [curRes]);
    
    /** 设置默认日期为上个月 */
    const setDefaultDate = () => {
        const today = new Date();
        const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1);
        return lastMonth
    };

    /** 初始化 */
    useEffect(() => {
        const data = searchForm.getFieldsValue()
        let queryData = {
            year: '',
            month: '',
        }
        if (data.date) {
            const date = new Date(data.date)
            queryData.year = date.getFullYear().toString()
            if (type == '2') {
              queryData.month = (date.getMonth() + 1).toString()
            }
        } else {
            const today = new Date();
            const date = new Date(today.getFullYear(), today.getMonth() - 1);
            queryData.year = date.getFullYear().toString()
            if (type == '2') {
              queryData.month = (date.getMonth() + 1).toString()
            }
        }
        manageServiceReturnRun(queryData);
    }, []);
  
    /**  搜索列表 */
    const onSearch = () => {
        const data = searchForm.getFieldsValue()
        let queryData = {
            year: '',
            month: '',
        }
        if (data.date) {
            const date = new Date(data.date)
            queryData.year = date.getFullYear().toString()
            if (type == '2') {
              queryData.month = (date.getMonth() + 1).toString()
            }
        } else {
            const today = new Date();
            const date = new Date(today.getFullYear(), today.getMonth() - 1);
            queryData.year = date.getFullYear().toString()
            if (type == '2') {
              queryData.month = (date.getMonth() + 1).toString()
            }
        }
        manageServiceReturnRun(queryData);
    };

    function onExportMultiHeaderExcel() {
      // 创建工作簿
      const workbook = new ExcelJs.Workbook();
      // 添加sheet
      const worksheet = workbook.addWorksheet('资产类别折旧');
      // 设置 sheet 的默认行高
      worksheet.properties.defaultRowHeight = 20;
      const headers = getTableColumn;
      // 第一行表头
      const names1: string[] = [];
      // 第二行表头
      const names2: string[] = [];
      // 第三行表头
      const names3: string[] = [];
      // 用于匹配数据的 keys
      const headerKeys: string[] = [];
      headers.forEach(item => {
        if (item.children && item.children.length > 0) {
          item.children.forEach(child => {
            if (child.children && child.children.length > 0) {
              child.children.forEach(c => {
                names1.push(item.header)
                names2.push(child.header)
                names3.push(c.header)
                headerKeys.push(c.key);
              })
            } else {
              names1.push(item.header)
              names2.push(child.header)
              names3.push(child.header)
              headerKeys.push(child.key);
            }
          })
        } else {
          names1.push(item.header)
          names2.push(item.header)
          names3.push(item.header)
          headerKeys.push(item.key);
        }
      })
      handleHeader(worksheet, headers, names1, names2, names3);
      // 添加数据
      addData2Table(worksheet, headerKeys, headers);
      // 给每列设置固定宽度
      worksheet.columns = worksheet.columns.map(col => ({ ...col, width: 20 }));
      // 导出excel
      saveWorkbook(workbook, '资产类别折旧.xlsx');
    }
  
    function handleHeader(
      worksheet: Worksheet,
      headers: any[],
      names1: string[],
      names2: string[],
      names3: string[],
    ) {
      // 判断是否有 children, 有的话是两行表头
      const isMultiHeader = headers?.some(item => item.children);
      if (isMultiHeader) {
        // 加表头数据
        const rowHeader1 = worksheet.addRow(names1);
        const rowHeader2 = worksheet.addRow(names2);
        const rowHeader3 = worksheet.addRow(names3);
        rowHeader1.height = 20
        rowHeader2.height = 20
        rowHeader3.height = 20
        // rowHeader1.eachCell((cell, colNum) => {
        //   cell.fill = {type: 'pattern', pattern: 'solid',fgColor: {argb: 'fafafa'}}
        //   cell.alignment  = {vertical: 'middle', horizontal: 'center', wrapText: false}
        //   cell.border  = {
        //     top: {style:'thin', color: {argb: 'f0f0f0'}},
        //     left: {style:'thin', color: {argb: 'f0f0f0'}},
        //     bottom: {style:'thin', color: {argb: 'f0f0f0'}},
        //     right: {style:'thin', color: {argb: 'f0f0f0'}},
        //   }
        // })
        // rowHeader2.eachCell((cell, colNum) => {
        //   cell.fill = {
        //     type: 'pattern',
        //     pattern: 'solid',
        //     fgColor: {argb: 'fafafa'},
        //   }
        //   cell.alignment  = {vertical: 'middle', horizontal: 'center', wrapText: false,}
        //   cell.border  = {
        //     top: {style:'thin', color: {argb: 'f0f0f0'}},
        //     left: {style:'thin', color: {argb: 'f0f0f0'}},
        //     bottom: {style:'thin', color: {argb: 'f0f0f0'}},
        //     right: {style:'thin', color: {argb: 'f0f0f0'}},
        //   }
        // })
        // rowHeader3.eachCell((cell, colNum) => {
        //   cell.fill = {
        //     type: 'pattern',
        //     pattern: 'solid',
        //     fgColor: {argb: 'fafafa'},
        //   }
        //   cell.alignment  = {vertical: 'middle', horizontal: 'center', wrapText: false,}
        //   cell.border  = {
        //     top: {style:'thin', color: {argb: 'f0f0f0'}},
        //     left: {style:'thin', color: {argb: 'f0f0f0'}},
        //     bottom: {style:'thin', color: {argb: 'f0f0f0'}},
        //     right: {style:'thin', color: {argb: 'f0f0f0'}},
        //   }
        // })
        mergeColumnCell(worksheet);
        return;
      }
      // 加表头数据
      const rowHeader = worksheet.addRow(names1);
    }
  
    const addData2Table = (worksheet: Worksheet, headerKeys: string[], headers: any[]) => {
      dataSource?.forEach((item: any) => {
        const rowData = headerKeys?.map(key => item[key]);
        const row = worksheet.addRow(rowData);
        row.height = 20;
        // 设置行样式, wrapText: 自动换行
        // row.alignment = { vertical: 'middle', horizontal: 'center', wrapText: false, shrinkToFit: false };
        // row.font = { size: 11, name: '微软雅黑' };
        // row.border  = {
        //   top: {style:'thin', color: {argb: 'f0f0f0'}},
        //   left: {style:'thin', color: {argb: 'f0f0f0'}},
        //   bottom: {style:'thin', color: {argb: 'f0f0f0'}},
        //   right: {style:'thin', color: {argb: 'f0f0f0'}},
        // }
      })
    }
    const saveWorkbook = (workbook: Workbook, fileName: string) => {
      // 导出文件
      workbook.xlsx.writeBuffer().then((data => {
        const blob = new Blob([data], {type: ''});
        saveAs(blob, fileName);
      }))
    }
    // 合并行和列，用于处理表头合并
    const mergeColumnCell = (
      worksheet: Worksheet,
    ) => {
      const mergeHeaders = ['A1:A3', 'B1:E1', 'B2:B3', 'C2:C3', 'D2:D3', 'E2:E3', 'F1:M1', 'F2:F3', 'G2:G3', 'H2:M2', 'N1:P1', 'N2:N3', 'O2:O3', 'P2:P3', 'Q1:T1', 'Q2:Q3', 'R2:R3', 'S2:S3', 'T2:T3']
      mergeHeaders.map(item => {
        worksheet.mergeCells(item)
      })
    }

    return (
        <>
            <div>
              <Card>
                  <div style={{display: 'flex', justifyContent: 'space-between'}}>
                      <Form form={searchForm}>
                          <Form.Item name='date' initialValue={moment(setDefaultDate())} style={{marginBottom: 0}}>
                              <DatePicker
                                picker='month'
                                format='YYYY-MM'
                                placeholder='请选择'
                                allowClear={false}
                              />
                          </Form.Item>
                      </Form>
                  <Button type={'primary'} icon={<SearchOutlined />} onClick={onSearch}>查询</Button>
                  </div>
              </Card>
              <div style={{marginTop: '10px', background: '#fff', position: 'relative'}}>
                <Tabs
                  className={pageStyles['commonTabs']}
                  type="card"
                  onChange={(activeKey: string) => {
                    setType(activeKey)
                    const data = searchForm.getFieldsValue()
                    let queryData = {
                        year: '',
                        month: '',
                    }
                    if (data.date) {
                        const date = new Date(data.date)
                        queryData.year = date.getFullYear().toString()
                        if (activeKey == '2') {
                          queryData.month = (date.getMonth() + 1).toString()
                        }
                    } else {
                        const today = new Date();
                        const date = new Date(today.getFullYear(), today.getMonth() - 1);
                        queryData.year = date.getFullYear().toString()
                        if (activeKey == '2') {
                          queryData.month = (date.getMonth() + 1).toString()
                        }
                    }
                    manageServiceReturnRun(queryData);
                  }}
                  items={[
                    {
                      label: '按年',
                      key: '1',
                      children: (
                        <>
                          <div style={{marginTop: '10px', padding: '0 8px'}}>
                            <Table ref={tableRef} columns={getTableColumn} bordered size="small" dataSource={dataSource} rowKey={(res) => res?.bigClass} scroll={{ x: 1200, y: 600 }} pagination={false} loading={manageServiceReturnLoading} />
                          </div>
                        </>
                      )
                    },
                    {
                      label: '按月',
                      key: '2',
                      children: (
                        <>
                          <div style={{marginTop: '10px', padding: '0 8px'}}>
                            <Table ref={tableRef} columns={getTableColumn} bordered size="small" dataSource={dataSource} rowKey={(res) => res?.bigClass} scroll={{ x: 1200, y: 600 }} pagination={false} loading={manageServiceReturnLoading} />
                          </div>
                        </>
                      )
                    },
                  ]}
                >
                </Tabs>
                <div className="tabsBodyBottomBtn" style={{ position: 'absolute', top: 5, right: 8 }}>
                  <Space>
                    <Button type="primary" icon={<DownloadOutlined />} onClick={onExportMultiHeaderExcel}>
                        下载
                      </Button>
                  </Space>
                </div>
              </div>
            </div>
        </>
    );

};

export default connect(({ baseLogin }: Record<string, any>) => ({
    curRes: baseLogin?.permissions,
}))(AssetDeprecitionClassManageView);